package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> entities = categoryService.getLevel1Categories();
        model.addAttribute("categories",entities);
        //视图解析器进行拼串
        //classpath:/templates/ + 返回值+ .html
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){

        //1 获取锁,锁名字一样就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        //2,加锁
        //阻塞等待,默认加的锁都是30S,Redisson的看门狗机制
        //锁的自动续期,如果业务超长,运行期间自动给锁续上新的30S,不用担心续期失效问题,
        lock.lock(); //10S以后自动解锁,自动解锁时间一定要大于业务执行时间
        //问题: lock.lock(10, TimeUnit.SECONDS); 在锁到期时不会自动续期
        //1、如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //如果我们未指定锁的超时时间，就使用30*1000【LockWatchdogTimeout看门狗的默认时间】;
        //只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗的默认时间】

        //最佳实战
        //lock.lock(10, TimeUnit.SECONDS);省掉整个续期操作,手动解锁

        try{
            System.out.println("加锁成功,执行业务..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){
            lock.unlock();
        }finally {
            //3 解锁
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }
    @ResponseBody
    @GetMapping("/write")
    public String write(){

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");

        String s="";
        RLock rLock = readWriteLock.writeLock();

        try {
            //改数据加写锁,读数据加读锁
            rLock.lock();
            s= UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("write",s);
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        String s="";
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        try {
            s=redisTemplate.opsForValue().get("write");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    /**
     * 车位停车
     * 3车位
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException{
        RSemaphore park = redissonClient.getSemaphore("park");


        park.acquire();//获取一个信号，获取到信号之后，信号量会减1


        return "ok";
    }

    @ResponseBody
    @GetMapping("/go")
    public String go()  throws InterruptedException{
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();//释放一个信号，释放之后，信号量会加1
        return "ok";
    }

    /**
     * 放假，锁门
     * 1班没人了,2
     * 5个班全部走完锁大门
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException{
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁都完成
        return "放假了";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id) throws InterruptedException{
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//计数减1
        return id+"班的人走了";
    }
}
